const bcrypt = require('bcryptjs');
const pool = require('../config/db');
const generateToken = require('../utils/generateToken');

/**
 * @desc    注册新用户
 * @route   POST /api/auth/register
 * @access  Public
 */
const register = async (req, res) => {
    try {
    const { username, password, role = 'user' } = req.body;

    // 验证请求数据
    if (!username || !password) {
        return res.status(400).json({ message: '请提供用户名和密码' });
    }

    // 检查用户名是否已存在
    const [users] = await pool.query(
        'SELECT * FROM users WHERE username = ?',
        [username]
    );

    if (users.length > 0) {
        return res.status(400).json({ message: '用户名已存在' });
    }

    // 验证角色是否有效
    if (!['admin', 'user'].includes(role)) {
        return res.status(400).json({ message: '角色必须是admin或user' });
    }

    // 密码加密
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);

    // 创建用户
    const [result] = await pool.query(
        'INSERT INTO users (username, password, role) VALUES (?, ?, ?)',
        [username, hashedPassword, role]
    );

    // 获取创建的用户
    const [newUser] = await pool.query(
        'SELECT id, username, role FROM users WHERE id = ?',
        [result.insertId]
    );

    res.status(201).json({
        message: '用户注册成功',
        user: newUser[0]
    });
    } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

/**
 * @desc    用户登录
 * @route   POST /api/auth/login
 * @access  Public
 */
const login = async (req, res) => {
    try {
    const { username, password } = req.body;

    // 验证请求数据
    if (!username || !password) {
        return res.status(400).json({ message: '请提供用户名和密码' });
    }

    // 查找用户
    const [users] = await pool.query(
        'SELECT * FROM users WHERE username = ?',
        [username]
    );

    if (users.length === 0) {
        return res.status(401).json({ message: '用户名或密码不正确' });
    }

    const user = users[0];

    // 验证密码
    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) {
        return res.status(401).json({ message: '用户名或密码不正确' });
    }

    // 生成菜单列表
    let menus;
    if (user.role === 'admin') {
        // 管理员菜单
        menus = [
        { id: 1, name: '总览', path: '/overview' },
        { id: 2, name: '学生管理', path: '/students' },
        { id: 3, name: '老师管理', path: '/teachers' },
        { id: 4, name: '班级管理', path: '/classes' },
        { id: 5, name: '个人信息', path: '/profile' }
        ];
    } else {
        // 普通用户菜单
        menus = [
        { id: 1, name: '总览', path: '/overview' },
        { id: 2, name: '学生管理', path: '/students' },
        { id: 5, name: '个人信息', path: '/profile' }
        ];
    }

    // 生成token
    const token = generateToken({ id: user.id, role: user.role });

    res.json({
        token,
        user: {
        id: user.id,
        username: user.username,
        role: user.role
        },
        menus
    });
    } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ message: '服务器错误' });
    }
};

module.exports = {
    register,
    login
};
